package com.dreamcar.auction.managedbean;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;

import com.dreamcar.auction.ejb.ReverseAuctionFacadeLocal;
import com.dreamcar.auction.entity.Bid;
import com.dreamcar.auction.entity.PurchaseOrder;
import com.dreamcar.auction.entity.Request;
import com.dreamcar.auction.enums.RequestStatusEnum;
import com.dreamcar.auction.exception.InvalidBidRequestException;
import com.dreamcar.auction.util.RequestHelper;
import com.dreamcar.inventory.ws.RequestDTO;

@ManagedBean(name="requestManager")
@SessionScoped
public class BidRequestManager {
	
	@EJB
	ReverseAuctionFacadeLocal reverseAuctionFacade;
	
	@ManagedProperty(value="#{carComponentManager}")
	CarComponentManager carComponentManager;
	
	private String status;
	private List<SelectItem> lstRequestItem;
	private List<SelectItem> lstBidItem;
	private List<Request> lstRequest;
	private List<Bid> lstBid;
	private String requestIdSelected;
	private String amountBid;
	private String bidIdSelected;
	private Request request;
	private Date date;
	
//	** No especificar en diagrama
	
	public BidRequestManager() {
//		Esto es para que le pueda settear los valores desde postBidRequest.xhtml
		request = new Request();
	}
	
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public Request getRequest() {
		return request;
	}
	public void setRequest(Request request) {
		this.request = request;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	public List<Request> getLstRequest() {
		return lstRequest;
	}
	public void setRequestIdSelected(String requestIdSelected) {
		this.requestIdSelected = requestIdSelected;
	}
	public String getRequestIdSelected() {
		return requestIdSelected;
	}
	public List<Bid> getLstBid() {
		return lstBid;
	}
	public void setLstBid(List<Bid> lstBid) {
		this.lstBid = lstBid;
	}
	public void setLstRequestItem(List<SelectItem> lstRequestItem) {
		this.lstRequestItem = lstRequestItem;
	}
	public void setLstBidItem(List<SelectItem> lstBidItem) {
		this.lstBidItem = lstBidItem;
	}
	public String getAmountBid() {
		return amountBid;
	}
	public void setAmountBid(String amountBid) {
		this.amountBid = amountBid;
	}
	public void setCarComponentManager(CarComponentManager carComponentManager) {
		this.carComponentManager = carComponentManager;
	}
	public String getBidIdSelected() {
		return bidIdSelected;
	}
	public void setBidIdSelected(String bidIdSelected) {
		this.bidIdSelected = bidIdSelected;
	}
	public boolean getShowRequestList(){
		return (lstRequest != null && !lstRequest.isEmpty());
	}
	public boolean getShowBidsList(){
		return (lstBid!=null && !lstRequest.isEmpty());
	}
	
//	** FIN No especificar en diagrama
	
	
	public List<SelectItem> getLstRequestItem() {
		lstRequestItem = new ArrayList<SelectItem>();
		for (Request request : lstRequest) {
			lstRequestItem.add(new SelectItem(request.getIdRequest(), request.getIdRequest().toString()));
		}
		return lstRequestItem;
	}
	public List<SelectItem> getLstBidItem() {
		lstBidItem = new ArrayList<SelectItem>();
		for (Bid bid: lstBid) {
			lstBidItem.add(new SelectItem(bid.getIdBid(),null));
			if(bid.getWinner()){
				bidIdSelected=bid.getIdBid().toString();
			}
		}
		return lstBidItem;
	}

	public String validateAndSaveRequest(){
		HttpServletRequest requestHttp = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
		
		RequestDTO requestDTO = RequestHelper.buildRequestDTO(
				new Integer(carComponentManager.getCmActual()).intValue(),
				new Integer(carComponentManager.getcActual()).intValue(),
				new Integer(carComponentManager.getDmActual()).intValue(),
				request.getQuantity().intValue());
		
		request.setFinishDate(new Timestamp(date.getTime()));
		request.setStatus(RequestStatusEnum.OPEN.toValue());
		
		try{
			reverseAuctionFacade.validateAndSaveRequest(requestDTO, request, 
					new Integer(carComponentManager.getcActual()), getUsername());

			requestHttp.setAttribute("result", "EXITO!!!");
			return "Success";
		}catch (InvalidBidRequestException e) {
			requestHttp.setAttribute("result", "Los datos ingresados no son validos");
			return "InvalidRequest";
		}
	}
	
	public void findOpenRequestByComponent(){
		Request example = new Request(null, null, null, null, null, RequestStatusEnum.OPEN.toValue(), null, null);
		lstRequest = reverseAuctionFacade.findRequestByExampleAndComponent(example, new Integer(carComponentManager.getcActual()));
		lstBid = null;
	}
	public void findClosedRequestByComponent(){
		Request example = new Request(null, null, null, null, null, RequestStatusEnum.CLOSED.toValue(), null, null);
		lstRequest = reverseAuctionFacade.findRequestByExampleAndComponent(example, new Integer(carComponentManager.getcActual()));
		lstBid = null;
	}
	public void findClosedRequestWithPOByComponent(){
		Request example = new Request(null, null, null, null, null, RequestStatusEnum.CLOSED.toValue(), new PurchaseOrder(), null);
		lstRequest = reverseAuctionFacade.findRequestByExampleAndComponent(example, new Integer(carComponentManager.getcActual()));
		lstBid = null;
	}
	
	public void getBidsRequest(){
		Set<Bid> bidsSet = reverseAuctionFacade.findBidsRequest(new Integer(requestIdSelected));
		lstBid = new ArrayList<Bid>();
		for (Bid bid : bidsSet) {
			lstBid.add(bid);
		}
	}
	
	public String submitBid(){
		Bid bid = new Bid();
		bid.setAmount(amountBid);
		HttpServletRequest requestHttp = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
		try {
			reverseAuctionFacade.submitBid(bid, new Integer(requestIdSelected), getUsername());
			requestHttp.setAttribute("result", "EXITO!!!");
			return "Success";
		} catch (InvalidBidRequestException e) {
			e.printStackTrace();
			requestHttp.setAttribute("result", "Debes ingresar una oferta menor o igual al precio establecido");
			return "InvalidRequest";
		}
	}
	
	public String issuePO(){
		HttpServletRequest requestHttp = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
		requestHttp.setAttribute("result", "EXITO!!!");
		String username = getUsername();
		reverseAuctionFacade.issuePO(new Integer(requestIdSelected), new Integer(bidIdSelected), username);
		return "Success";
	}
	
	public String scheduleWork(){
//		Se supone que el administrador selecciona el estatus
		status = RequestStatusEnum.SCHEDULED.toValue();
		RequestDTO requestDTO = RequestHelper.buildRequestDTO(
				new Integer(carComponentManager.getCmActual()).intValue(),
				new Integer(carComponentManager.getcActual()).intValue(),
				new Integer(carComponentManager.getDmActual()).intValue(),
				0);
		reverseAuctionFacade.scheduleWork(requestDTO, new Integer(requestIdSelected), RequestStatusEnum.fromValue(status));
		
		HttpServletRequest requestHttp = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
		requestHttp.setAttribute("result", "EXITO!!!");
		return "Success";
	}
	
	
	private String getUsername(){
		String username = null;
//		TODO: Aqui obtenemos el usuario del Principal
//		username = requestHttp.getUserPrincipal().getName();
		return "user";
	}
	

}
